<template>
  <div class="home">
    <div class="head">
      <div class="form">
        <div class="formItem">
          <span>姓名：</span>
          <el-input
            size="small"
            style="width: 272px"
            v-model="state.searchObj.user"
            placeholder="请输入"
          ></el-input>
        </div>
        <div class="formItem">
          <span>权限：</span>
          <el-select
            size="small"
            clearable
            style="width: 272px"
            v-model="state.searchObj.jurisdiction"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in state.jurisdictionArr"
              :key="index"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="btn">
        <el-button size="small" @click="onRest">重置</el-button>
        <el-button size="small" type="primary" @click="onSearch"
          >查询</el-button
        >
      </div>
    </div>
    <div class="content">
      <h5>成员管理</h5>
      <div class="list">
        <el-table :data="state.tableData" style="width: 100%">
          <el-table-column label="成员姓名">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                style="width: 70%"
                size="small"
                v-model="scope.row.nickname"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否启用">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                @change="changeStatus($event, scope.row.id)"
              ></el-switch>
            </template>
          </el-table-column>
          <!-- <el-table-column label="ID">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.id"
              ></el-input>
            </template>
          </el-table-column> -->
          <el-table-column label="账号">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.username"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="工号">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.number"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="密码">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.pwd"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="薪资">
            <template #default="scope">
              <el-input
                v-if="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="salary"
                v-model="scope.row.salary_name"
                type="password"
                :show-password="true"
              ></el-input>
              <el-input
                v-else
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="salary"
                v-model="scope.row.salary"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="权限">
            <template #default="scope">
              <el-select
                v-if="scope.row.isEdit"
                size="small"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                style="width: 70%"
                v-model="scope.row.group_id"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in state.jurisdictionArr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-input
                v-if="!scope.row.isEdit"
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.name"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="部门">
            <template #default="scope">
              <el-select
                :disabled="!scope.row.isEdit"
                size="small"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                style="width: 70%"
                v-model="scope.row.department_id"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in state.department"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>

            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template #default="scope">
              <div v-if="scope.row.isEdit" class="editing">
                <span @click="handleSave(scope.index_, scope.row)">保存</span>
                <span @click="handleCancle(scope.index_, scope.row)">取消</span>
              </div>
              <div v-if="!scope.row.isEdit" class="readOnly">
                <span @click="handleEdit(scope.index_, scope.row)">编辑</span>
                <span @click="handleDelete(scope.row.id)">删除</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="addUser" @click="addUser"><strong>+</strong>新增成员</div>
       <el-pagination
          @current-change="handleCurrentChange"
          :current-page="state.page"
          :page-size="state.pageSize"
          background
          :total="state.total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
// vue3 弃用了beforeCreate created
import {
  getCurrentInstance,
  ref,
  reactive,
  onMounted,
  onUpdated,
  onUnmounted,
} from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
const state = reactive({
  searchObj: {
    user: "",
    jurisdiction: "",
  },
  formObj: {
    id: "",
    name: "",
    account: "",
    pwd: "",
    jurisdiction: "",
    isEdit: true,
    status: 0,
  },
  page: 1,
  pageSize: 8,
  total: 0,
  addIndex: -1,
  selectVal: 1,
  adding: false,
  jurisdictionArr: [],
  tableData: [],
});

function onRest() {
  state.searchObj.user = "";
  state.searchObj.jurisdiction = "";
}
function handleEdit(index, rowObj) {
  console.log(index);
  console.log(rowObj);
  state.tableData[index].canEdit = true;
  state.tableData[index].isEdit = true;
}


function handleCancle(index, rowObj) {
  console.log(index);
  console.log(rowObj);
  state.tableData[index].isEdit = false;
}
function handleSizeChange() {}
export default {
  name: "User",
  components: {},
  // setup(props,ctx){
  setup(props, { emit }) {
    const  ctx  = getCurrentInstance();
    const _this = ctx.appContext.config.globalProperties;
    function addUser() {
      if (!state.adding) {
        state.addIndex = state.tableData.length;
        let newObj = {
          isEdit: true,
        };
        // let newObj = state.formObj
        state.tableData.push(newObj);
      } else {
        _this.$message.error("请先填写成员信息保存后才能继续添加！");
        return;
      }
      state.adding = true;
    }
    //遍历data转换formdata
    function changeData(data) {
      let formData = new FormData();
      for (const key in data) {
        formData.append(key, data[key]);
      }
      return formData;
    }

    //获取分组列表
    const getRoleList = () => {
      _this
        .$request({
          url: "?s=Learn.Admin.GetGroups"
        })
        .then((res) => {
          if (res.ret == 200) {
            state.jurisdictionArr = res.data.data;

          }
        });
    };
    //获取管理员列表
    const getAdminList = () => {
      _this
        .$request({
          url: "?s=Learn.Admin.adminList",
          params: {
            page: state.page,
            pageSize: state.pageSize,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            state.total = res.data.total;
            state.tableData = res.data.data.map((e) => {
              e.canEdit = false;
              e.status = parseInt(e.status) > 0 ? true : false;
              return e;
            });
          }
        });
    };
    //启用禁用管理员接口
    const adminStatus = (oldStatus, admin_id) => {
      let status = oldStatus ? 1 : 0;
      _this
        .$request({
          url: "?s=Learn.Admin.AdminStatus",
          params: {
            status,
            admin_id,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            if (status > 0) {
              ElMessage.success({
                message: "已启用管理员权限",
                type: "success",
              });
            } else {
              ElMessage.success({
                message: "已关闭管理员权限",
                type: "success",
              });
            }
          }
        });
    };
    function handleDelete(id) {
      _this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.$request({
          url: "?s=Learn.Admin.AdminStatus",
          params: {admin_id:id},
        }).then((res) => {
          if(res.ret == 200){
            _this.$message({
              type: 'success',
              message: '删除成功!'
            });
              getAdminList();
          }else{
              ElMessage.error(res.msg);
          }
        })

      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
    //启用禁用管理员
    const changeStatus = (e, id) => {
      console.log(e, id);
      adminStatus(e, id);
    };
    //添加管理员
    const addAdmin = (data) => {
      _this
        .$request({
          url: "?s=Learn.Admin.addAdmin",
          params: data,
        })
        .then((res) => {
          if (res.ret == 200) {
            ElMessage.success({
              message: "添加成功",
              type: "success",
            });
            getAdminList();
          } else {
            ElMessage.error({
              message: res.msg,
            });
          }
        });
    };
    //删除接口
    const delAdmin = (admin_id) => {
      _this
        .$request({
          url: "?s=Learn.Admin.admin_del",
          params: {
            admin_id,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            ElMessage.success({
              message: "删除成功",
            });
          } else {
            ElMessage.error({
              message: res.msg,
            });
          }
        });
    };
    //编辑管理员
    const editAdmin = (data) => {
      _this
        .$request({
          url: "?s=Learn.Admin.editAdmin",
          params: data,
        })
        .then((res) => {
          if (res.ret == 200) {
            ElMessage.success({
              message: "编辑成功",
              type: "success",
            });
            getAdminList();
          } else {
            ElMessage.error({
              message: res.msg,
              type: "error",
            });
            getAdminList();
          }
        });
    };
    //点击保存
    function handleSave(index, rowObj) {
      if(rowObj.department_id == '未选择'){
          ElMessage.error({
            message: "请选择所属部门",
          });
          return
      }
      if(isChinese(rowObj.department_id)){
        rowObj.department_id = rowObj.d_id;
      }
      let data = {
        group_id: rowObj.group_id,
        nickname: rowObj.nickname,
        username: rowObj.username,
        password: rowObj.pwd,
        status: rowObj.status ? 1 : 0,
        salary: rowObj.salary ? rowObj.salary : 0,
        department_id: rowObj.department_id,
        number: rowObj.number
      };
      if (rowObj.canEdit) {
        data.admin_id = state.tableData[index].id;
        editAdmin(data);
      } else {
        addAdmin(data);
      }
      state.tableData[index].isEdit = false;
      if (index == state.addIndex) {
        console.log("新增的对象");
        state.addIndex = -1;
        state.adding = false;
      }
    }
    const handleCurrentChange = (val) => {
      if (val !== state.page) {
          state.page = val
          return getAdminList()
      }
    }
    const isChinese = (str) => {
      var re=/[^\u4E00-\u9FA5]/;
      if (re.test(str)) return false ;
      return true ;
    }
    const getDepartment = () => {
      _this
        .$request({
          url: "?s=Learn.Department.Lists",
          params: {
            page: 1,
            pageSize: 20
          },
        })
        .then((res) => {
            if (res.ret == 200) {
                state.department = res.data.data
            }
        })
    }

    onMounted(() => {
      getRoleList();
      getAdminList();
      getDepartment();
    });
    return {
      state,
      adminStatus,
      changeStatus,
      getRoleList,
      getAdminList,
      addAdmin,
      editAdmin,
      onRest,
      addUser,
      handleEdit,
      handleDelete,
      handleSave,
      handleCancle,
      handleSizeChange,
      handleCurrentChange,
    };
  },
};
</script>
<style lang="scss" scoped>
.noEdit {
  /deep/ input {
    border: 0;
    padding: 0;
  }
}
.home {
  .head {
    background-color: #ffffff;
    margin-bottom: 16px;
    padding: 24px 60px 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;
    .form {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .formItem {
        margin-bottom: 24px;
      }
      span {
        color: #000000d9;
        font-size: 14px;
      }
      &:nth-child(1) .formItem {
        margin-right: 45px;
      }
    }
    .btn {
      margin-bottom: 24px;
    }
  }

  .content {
    width: 100%;
    background-color: #ffffff;
    padding-bottom: 50px;
    h5 {
      font-size: 16px;
      padding: 20px 56px;
      border-bottom: 1px solid #e9e9e9ff;
    }

    .list {
      margin: 20px 32px;
      .readOnly,
      .editing {
        display: flex;
        span {
          color: #1890ffff;
          margin-right: 8px;
          padding-right: 8px;
          cursor: pointer;
          &:nth-child(1) {
            border-right: 1px solid #e9e9e9ff;
          }
        }
      }
      .addUser {
        margin-top: 23px;
        border-radius: 4px;
        color: #000000a6;
        border: 1px dashed #d9d9d9ff;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        margin-bottom: 10px;
        strong {
          margin-right: 5px;
        }
      }
    }
  }
}
</style>
